<template>
  <AdminHeader></AdminHeader>
  <div class="admin-novels">
    <div class="row text-center justify-content-center webtitle">《{{novel_info.novel_name}}》章节</div>
    <el-button type="success" @click="addChapter">+ 增加章节</el-button>
    <el-table :data="chapters" stripe style="width: 100%" class="novel-table">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="chapter_title" label="章节名称"></el-table-column>
      <el-table-column prop="update_time" label="更新时间"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="editChapter(scope.row.id)">编辑</el-button>
          <el-button type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalNovels"
          class="pagination">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import {ElMessageBox, ElNotification} from "element-plus";
import AdminHeader from "@/components/AdminHeader.vue";
import router from "@/router/index.js";
import {useRoute} from "vue-router";
import VueCookies from "vue-cookies";
import config from "../../../config/config.js";

export default {
  components: {
    AdminHeader,
  },
  setup() {
    const chapters = ref([]);
    const novel_info = ref([]);
    const route = useRoute(); // 获取当前路由

    const fetchNovelInfo = async () => {
      const novelId = route.params.novelId;
      const apiUrl = `${config.apiUrl}/novel/info?novelId=${novelId}`;

      try {
        const response = await axios.get(apiUrl);
        const novelInfo = response.data;
        if (response.status === 201) {
          ElNotification({
            message: novelInfo.message,
            type: 'warning',
            duration: 2000
          });
          router.back(); // 自动返回
        } else {
          novel_info.value = novelInfo;
        }
      } catch (error) {
        console.error('获取小说信息失败:', error);
        ElNotification({
          message: '暂无信息',
          type: 'warning',
          duration: 2000
        });
        router.back(); // 自动返回
      }
    };

    const fetchChapters = async () => {
      const novelId = route.params.novelId; // Replace with the actual novelId
      const apiUrl = `${config.apiUrl}/novel-chapter/list?novelId=${novelId}`;

      try {
        const response = await axios.get(apiUrl);
        chapters.value = response.data;
      } catch (error) {
        console.error('Failed to fetch chapters:', error);
        ElNotification({
          message: 'Failed to fetch chapters',
          type: 'error',
          duration: 2000
        });
      }
    };

    const editChapter = (chapterId) => {
      const editUrl = `/admin/chapter/edit/${chapterId}`;
      router.push(editUrl);
    };
    const addChapter = () => {
      const novelId = route.params.novelId; // Replace with the actual novelId
      const addUrl = `/admin/chapter/add/${novelId}`;
      router.push(addUrl);
    };

    const deleteChapter = async (chapterId) => {
      const adminToken = VueCookies.get('adminToken');
      const apiUrl = `${config.apiUrl}/novel-chapter/delete?chapterId=${chapterId}`;
      const headers = {
        Authorization: `Bearer ${adminToken}`
      };

      try {
        const response = await axios.get(apiUrl, {headers});
        if (response.status === 200) {
          ElNotification({
            message: response.data.message,
            type: 'success',
            duration: 2000
          });
          fetchChapters(); // 重新获取章节信息
        } else {
          ElNotification({
            message: response.data.message,
            type: 'error',
            duration: 1400
          });
        }
      } catch (error) {
        ElNotification({
          message: error,
          type: 'error',
          duration: 2000
        });
      }
    };
    const confirmDelete = (chapterId) => {
      ElMessageBox.confirm('确定删除该章节？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteChapter(chapterId);
      });
    };

    onMounted(() => {
      fetchChapters();
      fetchNovelInfo();
    });


    return {
      chapters,
      editChapter,
      deleteChapter,
      confirmDelete,
      addChapter,
      fetchNovelInfo,
      novel_info
    };
  }
};
</script>

<style scoped>
.webtitle {
  font-size: 20px;
  padding: 10px;
  letter-spacing: 2px;
}
 .admin-novels {
   padding: 20px;
 }

.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-type {
  width: 100px;
  margin-right: 10px;
}

.search-input {
  width: 80%;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.novel-table {
  margin-top: 20px;
}
</style>
